const PULL_MEI_TUAN_CANCELED = "pullMeiTuanCanceled";
const PULL_MEI_TUAN_AWAIT_CHECKIN = "pullMeiTuanAwaitCheckin";
const PULL_CTRIP = "pullCtrip";
const MFB_DOMAIN = "www.manfangbao.com";
const DEV_MFB_DOMAIN = "dev.manfangbao.com";
const XZL_DOMAIN = "www.xzlpms.com";

const ResponseTargetUrls = ["localhost", MFB_DOMAIN, DEV_MFB_DOMAIN, XZL_DOMAIN]

function sendMessageToTab(targetPageUrls = [], message) {
    try {
        chrome.tabs.query({}).then((res) => {
            const tab = res.find((t) =>
              targetPageUrls.some((url) => t.url?.includes(url))
            );

            if (!tab) {
                return;
            }

            chrome.tabs.sendMessage(tab.id, message);
        }).catch((e) => {
            console.error(e);
        });
    } catch (e) {
        console.error(e);
    }
}

function handleMeiTuan(msgType, pageIdx) {
    sendMessageToTab(["https://me.meituan.com/ebooking", "https://eb.meituan.com/ebooking", "https://eb.meituan.com/ebk", "https://ebooking.meituan.com/ebooking", "https://ebooking.meituan.com/ebk"], {
        msgType,
        pageIdx,
    });
}

function handleCtrip(pageIdx) {
    sendMessageToTab(["https://ebooking.ctrip.com"], {
        msgType: PULL_CTRIP,
        pageIdx,
    });
}

async function forwardMeiTuanRequest(message) {
    try {
        if (!message?.data) {
            return
        }

        const {headers, url} = message.data
        const {data} = await fetch(url, {
            method: "GET",
            headers,
        }).then(res => {
            return res.json()
        })
        const targetUrls = message?.bizType === "detail" ? ResponseTargetUrls : ["https://me.meituan.com/ebooking"]

        sendMessageToTab(targetUrls, {
            ...message,
            data,
            url
        })
        await sleep(500 + Math.random() * 3000)
    } catch (e) {
        console.error(e)
    }
}

chrome.runtime.onMessage.addListener((message) => {
    try {
        if (typeof message === "object") {
            const msgType = message?.msgType;

            switch (msgType) {
                case PULL_MEI_TUAN_CANCELED:
                case PULL_MEI_TUAN_AWAIT_CHECKIN:
                    // 如果重新发送则需要延迟，需要等待页面刷新完成
                    setTimeout(() => {
                        handleMeiTuan(msgType, message?.data?.pageIdx);
                    }, message.resend ? 5000 : 0)
                    break;
                case PULL_CTRIP:
                    handleCtrip(message?.data?.pageIdx);
                    break;
                case "response":
                    sendMessageToTab(ResponseTargetUrls, message);
                    break;
                case "forward":
                    forwardMeiTuanRequest(message)
                    break;
            }
        }
    } catch (e) {
        console.log(e);
    }
});

async function sleep(timeout) {
    return new Promise((resolve) => setTimeout(resolve, timeout));
}
